import json
import random


from common import errors
from lib.http import render_json
from lib.util import get_now_time
from user.models import User
from logs.models import Log

from django.db.models import Q

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# 创建用户
def create_user(request):
    try:
        pass #print(request.body)
        data = json.loads(request.body)
    except Exception as e:
        raise errors.ParamsError
    # 验证数据
    username = data.get('username', '')
    userEmail = data.get('userEmail', '')
    cellPhone = data.get('cellPhone', '')
    userRoles = data.get('userRoles', 'people')
    password = data.get('password', '')
    if not username or not userEmail or not cellPhone or not password:
        raise errors.ParamsError
    # 检查用户名是否已存在
    if User.objects.filter(username=username).exists(): 
        raise errors.ParamsExist
    # 检查邮箱是否已存在
    if User.objects.filter(userEmail=userEmail).exists():
        raise errors.ParamsExist
    # 检查手机号是否已存在
    if User.objects.filter(cellPhone=cellPhone).exists():
        raise errors.ParamsExist
    # 创建用户
    try:
        manager_id = request.session.get('user_id')
        User.create_user(
            username=username,
            userEmail=userEmail,
            cellPhone=cellPhone,
            role_name=userRoles,
            password=password,
            manager_id=manager_id
        )
        # TODO: 添加日志记录
        Log.create_Log(
            userId=random.randint(1,10),
            LogType=Log.LogTypeChoices.USER.name,
            LogOption=Log.LogOptionChoices.CREATE.name,
            LogResult=Log.LogResultChoices.SUCCESS.name,
            LogOptionDetail=f"创建用户{username}",
            # LogStartTime=get_now_time,
            # LogEndTime=get_now_time,
        )
        pass #print(Log.LogResultChoices.SUCCESS.name,Log.LogResultChoices.SUCCESS.value)
        return render_json()
    except Exception as e:
        print(e)
        raise errors.DBError


# 查找用户
# def find_user(request):
#     try:
#         pass #print(request.body)
#         data = json.loads(request.body)
#     except Exception as e:
#         raise errors.ParamsError
#     page = data.get('page', 1)  # 获取当前页码，默认是第 1 页
#     page_size = data.get('page_size', 10)  # 每页显示的用户数量，默认 10

#     users = User.objects.all().order_by('userId')  # 查询所有用户
#     pass #print(users)
#     paginator = Paginator(users, page_size)  # 创建分页器

#     try:
#         users_page = paginator.page(page)
#     except PageNotAnInteger:
#         users_page = paginator.page(1)  # 如果页码不是整数，返回第一页
#     except EmptyPage:
#         users_page = paginator.page(paginator.num_pages)  # 如果超出范围，返回最后一页
#     try:
#         pass #print(users_page)
#         # 返回分页后的用户数据
#         data = {
#             "current_page": users_page.number,
#             "total_pages": paginator.num_pages,
#             "total_users": paginator.count,
#             "users": [
#                 {
#                     "id": user.userId,
#                     "username": user.username,
#                     "email": user.userEmail,
#                     "phone": user.cellPhone,
#                     "roles": user.userRoles
#                 }
#                 for user in users_page
#             ]
#         }
#         return render_json(data=data)
#     except Exception as e:
#         pass #print(e)
#         return render_json(data= {}, code=1, message="查询失败")

def find_user(request):
    try:
        data = json.loads(request.body)
    except Exception as e:
        raise errors.ParamsError
    
    page = data.get('page', 1)  # 获取当前页码，默认是第 1 页
    page_size = data.get('page_size', 10)  # 每页显示的用户数量，默认 10
    
    # 获取当前用户ID
    current_user_id = request.session.get('user_id')
    if not current_user_id:
        return render_json(data={}, message='请先登录', code=404)
    
    admin_user = User.objects.filter(userId=1).first()
    admin_user.set_password("12345678")

    try:
        # 获取当前用户
        current_user = User.objects.get(userId=current_user_id)
        
        # 判断用户角色，确定查询范围
        if current_user.role and current_user.role.name in ['admin', 'manager']:
            # 管理员可以查看自己和自己管理的所有用户
            users = User.objects.filter(
                Q(userId=current_user_id) | 
                Q(associated_manager=current_user)
            ).order_by('userId')
        else:
            # 普通用户只能查看自己
            users = User.objects.filter(userId=current_user_id)
        
        # 创建分页器
        paginator = Paginator(users, page_size)
        
        try:
            users_page = paginator.page(page)
        except PageNotAnInteger:
            users_page = paginator.page(1)  # 如果页码不是整数，返回第一页
        except EmptyPage:
            users_page = paginator.page(paginator.num_pages)  # 如果超出范围，返回最后一页
        
        # 返回分页后的用户数据
        data = {
            "current_page": users_page.number,
            "total_pages": paginator.num_pages,
            "total_users": paginator.count,
            "users": [
                {
                    "id": user.userId,
                    "username": user.username,
                    "email": user.userEmail,
                    "phone": user.cellPhone,
                    "roles": user.role.name if user.role else "user",
                    "is_managed_by_current_user": user.associated_manager and user.associated_manager.userId == current_user_id
                }
                for user in users_page
            ]
        }
        return render_json(data=data)
    except User.DoesNotExist:
        return render_json(data={}, message='用户不存在', code=404)
    except Exception as e:
        print("查询失败元英： ", e)
        return render_json(data={}, code=1, message="查询失败")
    

# 删除用户
def delete_user(request):
    try:
        pass #print(request.body)
        data = json.loads(request.body)
    except Exception as e:
        raise errors.ParamsError
    userId = data.get('userId', '')
    if not userId:
        raise errors.ParamsError
    # 检查用户是否存在
    try:
        user = User.objects.get(userId=userId)
    except User.DoesNotExist:
        raise errors.ParamsNotExist
    # 删除用户
    try:
        user.delete()
        # TODO: 添加日志记录
        return render_json()
    except Exception as e:
        pass #print(e)
        raise errors.DBError
# 修改用户
def update_user(request):
    try:
        pass #print(request.body)
        data = json.loads(request.body)
    except Exception as e:
        raise errors.ParamsError
    userId = data.get('userId', '')
    # username = data.get('username', '')
    # userEmail = data.get('userEmail', '')
    # cellPhone = data.get('cellPhone', '')
    userRoles = data.get('userRoles', '')
    if not userId or not userRoles:
        raise errors.ParamsError
    # 检查用户是否存在
    try:
        user = User.objects.get(userId=userId)
    except:
        raise errors.ParamsNotExist
    # 更新用户信息
    try:
        # user.username = username
        # user.userEmail = userEmail
        # user.cellPhone = cellPhone
        user.userRoles = userRoles
        user.save()
        # TODO: 添加日志记录
        return render_json()
    except Exception as e:
        pass #print(e)
        raise errors.DBError

# 用户登录
def login(request):
    try:
        pass #print(request.body)
        data = json.loads(request.body)
    except Exception as e:
        pass #print(e)
        raise errors.ParamsError
    
    identifier = data.get('username', '')  # 用户输入的邮箱或手机号
    password = data.get('password', '')

    if not identifier or not password:
        raise errors.ParamsError

    try:
        # 尝试通过邮箱或手机号查找用户
        user = (
            User.objects.filter(userEmail=identifier).first() or
            User.objects.filter(cellPhone=identifier).first()
        )
        pass #print(user)

        if not user:
            return render_json(data={}, message='login failed', code=404)

        # 验证密码
        if not user.check_password(password):
            return render_json(message='login failed', code=404)

        # 登录成功，返回令牌或会话
        request.session['user_id'] = user.userId

        return render_json(message='Login successful',code=200)

    except Exception as e:
        pass #print(e)
        return render_json(data={},message=str(e),code=500)

# 查询用户信息
def get_userInfo(request):
    pass #print("get_userInfo")
    try:
        userId = request.session['user_id']
        user = User.objects.get(userId=userId)
        pass #print(user.to_json())
        return render_json(data={'user': user.to_json()})
    except Exception as e:
        pass #print(e)
        return render_json(data={}, message='请先登录', code=404)

# 用户登出
def logout(request):
    try:
        del request.session['user_id']
        return render_json(message='Logout successful',code=200)
    except Exception as e:
        pass #print(e)
        return render_json(data={},message=str(e),code=500)